
package com.be.beadmin.quality.impl;

import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.product.entity.WorkOrderInfor;
import com.be.beadmin.product.impl.WorkOrderInforServiceImpl;
import com.be.beadmin.product.repository.WorkOrderInforRepository;
import com.be.beadmin.quality.dto.input.CabinetErrorDto;
import com.be.beadmin.quality.dto.input.CabinetQualityDto;
import com.be.beadmin.quality.dto.output.CabinetQualityEx;
import com.be.beadmin.quality.entity.CabinetError;
import com.be.beadmin.quality.entity.CabinetQuality;
import com.be.beadmin.quality.entity.CabinetQuality_;
import com.be.beadmin.quality.mapper.CabinetQualityMapper;
import com.be.beadmin.quality.mapper.CabinetQualityMapperEx;
import com.be.beadmin.quality.repository.CabinetErrorRepository;
import com.be.beadmin.quality.repository.CabinetQualityRepository;
import com.be.beadmin.quality.service.CabinetErrorService;
import com.be.beadmin.quality.service.CabinetQualityService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @description 服务实现
* @author zjm
* @date 2023-05-15
**/
@Service
@RequiredArgsConstructor
public class CabinetQualityServiceImpl implements CabinetQualityService {

    @Autowired
    private  CabinetQualityRepository cabinetQualityRepository;
    @Autowired
    private CabinetErrorRepository cabinetErrorRepository;
    @Autowired
    private  CabinetQualityMapper cabinetQualityMapper;
    @Autowired
    private  CabinetQualityMapperEx cabinetQualityExMapper;
    @Autowired
    private CabinetErrorService cabinetErrorService;
    @Autowired
    private WorkOrderInforServiceImpl workOrderInforService;

    @Override
    public Page<CabinetQualityEx> getCabinetQualityByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<CabinetQuality> page = cabinetQualityRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(CabinetQuality_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(CabinetQuality_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<CabinetQualityEx> page1 = page.map(cabinetQualityExMapper::toEntity);
            return page1;
    }

    @Override
    public void addCabinetQuality(CabinetQualityDto cabinetQualityDto) {
            CabinetQuality result = cabinetQualityRepository.findCabinetQualityByIdAndDelete(cabinetQualityDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("CabinetQuality不存在,请重新查询");
            }
            //工单编号wo唯一
            CabinetQuality result1 = cabinetQualityRepository.findCabinetQualityByWoAndDelete(cabinetQualityDto.getWo(), 0);
            if(ObjectUtil.isNotEmpty(result1)) {
                throw new BeadminException("该工单已完成接线质量填报,请重新选择工单号");
            }

            CabinetQuality cabinetQuality = cabinetQualityMapper.toEntity(cabinetQualityDto);

            cabinetQualityRepository.save(cabinetQuality);

    }

    @Override
    public void updateCabinetQuality(CabinetQualityDto cabinetQualityDto) {
            CabinetQuality cabinetQuality = cabinetQualityRepository.findCabinetQualityById(cabinetQualityDto.getId());
            cabinetQuality = cabinetQualityMapper.toEntity(cabinetQualityDto);
            cabinetQualityRepository.save(cabinetQuality);
    }


    @Override
    public void delCabinetQuality(String id) {
        CabinetQuality cabinetQuality = cabinetQualityRepository.findCabinetQualityById(id);
        List<CabinetError> cabinetErrors = cabinetErrorRepository.findCabinetErrorByCabinetQualityIdAndDelete(id, 0);
        if (cabinetErrors.size() != 0) {
            throw new BeadminException("有接线错误，不能删除");
        }
        cabinetQuality.setDelete(1);
        cabinetQualityRepository.save(cabinetQuality);
    }

    @Override
    public void delCabinetQualitys (List<String> ids) { }

    @Override
    public void addCabinetQualityAndCabinetError(CabinetQualityDto cabinetQualityDto, CabinetErrorDto[] cabinetErrorDtos) {
        //新增接线主表
        Integer errorLineCount = 0;
        for (int i = 0; i < cabinetErrorDtos.length; i++) {
            errorLineCount += cabinetErrorDtos[i].getErrorLineCount();
        }
        cabinetQualityDto.setErrorLineCount(errorLineCount);
        CabinetQuality one = getCabinetQualityInformationByWo(cabinetQualityDto.getWo());
        cabinetQualityDto.setBatchCount(one.getBatchCount());
        cabinetQualityDto.setCurrentBatch(one.getCurrentBatch());
        cabinetQualityDto.setBatchPlanCode(one.getBatchPlanCode());
        cabinetQualityDto.setProductCode(one.getProductCode());
        cabinetQualityDto.setProductName(one.getProductName());
        addCabinetQuality(cabinetQualityDto);
        CabinetQuality cabinetQuality = cabinetQualityRepository.findCabinetQualityByWoAndDelete(cabinetQualityDto.getWo(), 0);
        //新增错误子表
        for (int i = 0; i < cabinetErrorDtos.length; i++) {
            cabinetErrorDtos[i].setCabinetQualityId(cabinetQuality.getId());//通过wo找大表id wo和id一一对应
            cabinetErrorService.addCabinetError(cabinetErrorDtos[i]);
        }
    }

    @Override
    public void editCabinetQualityAndCabinetError(CabinetQualityDto cabinetQualityDto, CabinetErrorDto[] cabinetErrorDtos) {

        //先删除原错误子表信息
        List<CabinetError> cabinetErrors = cabinetErrorRepository.findCabinetErrorByCabinetQualityIdAndDelete(cabinetQualityDto.getId(),0);
        CabinetError error = new CabinetError();
        for(int i=0 ; i<cabinetErrors.size() ; i++){
            error = cabinetErrors.get(i);
            cabinetErrorService.delCabinetError(error.getId());
        }
        //编辑接线主表
        Integer errorLineCount = 0;
        for (int i = 0; i < cabinetErrorDtos.length; i++) {
            errorLineCount += cabinetErrorDtos[i].getErrorLineCount();
        }
        cabinetQualityDto.setErrorLineCount(errorLineCount);
        CabinetQuality one = getCabinetQualityInformationByWo(cabinetQualityDto.getWo());
        cabinetQualityDto.setBatchCount(one.getBatchCount());
        cabinetQualityDto.setCurrentBatch(one.getCurrentBatch());
        cabinetQualityDto.setBatchPlanCode(one.getBatchPlanCode());
        cabinetQualityDto.setProductCode(one.getProductCode());
        cabinetQualityDto.setProductName(one.getProductName());
        updateCabinetQuality(cabinetQualityDto);

        //编辑错误子表
        for (int i = 0; i < cabinetErrorDtos.length; i++) {
            cabinetErrorDtos[i].setCabinetQualityId(cabinetQualityDto.getId());//通过wo大表id
            cabinetErrorService.addCabinetError(cabinetErrorDtos[i]);
        }
    }

    @Override
    public CabinetQuality getCabinetQualityInformationByWo(String wo) {
        WorkOrderInfor workOrderInfor = workOrderInforService.getWorkOrderInforByWo(wo);
        CabinetQuality cabinetQuality = new CabinetQuality();
        cabinetQuality.setBatchCount(workOrderInfor.getBatchCount());
        cabinetQuality.setBatchPlanCode(workOrderInfor.getBatchPlanCode());
        cabinetQuality.setCurrentBatch(workOrderInfor.getCurrentBatch());
        cabinetQuality.setWo(workOrderInfor.getWo());
        cabinetQuality.setProductName(workOrderInfor.getProductName());
        cabinetQuality.setProductCode(workOrderInfor.getBatchProductCode());
        return cabinetQuality;
    }

}